<template>
  <el-card class="box-card" style="width: 1180px">
    <div class="search">
      <el-row gutter="20">
        <el-col :span="6">
          <el-input
            size="medium"
            placeholder="请输入用户名"
            v-model="query.adminNickname"
          >
          </el-input>
        </el-col>

        <el-col :span="6">
          <el-input
            size="medium"
            placeholder="请输入账号状态"
            v-model="query.adminStatus"
          >
          </el-input>
        </el-col>

        <el-col :span="2">
          <el-button type="primary" size="medium" @click="loadAdmin()"
            >查询</el-button
          >
        </el-col>

        <el-col :span="8">
          <el-button type="info" size="medium" @click="reset()">重置</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="info" size="medium" @click="dialog.addshow = true"
            >注册</el-button
          >
        </el-col>
      </el-row>
    </div>

    <!--表格-->
    <el-table :data="adminList" stripe style="width: 100%">
      <el-table-column prop="adminNickname" label="用户名"> </el-table-column>

      <el-table-column prop="adminGender" label="性别"> </el-table-column>

      <el-table-column prop="deptId" label="所属部门"> </el-table-column>
      <el-table-column prop="adminTel" label="手机号码"> </el-table-column>

      <el-table-column prop="adminStatus" label="状态"> </el-table-column>

      <el-table-column prop="adminCreatedTime" label="创建时间">
      </el-table-column>

      <el-table-column prop="adminAvatar" label="头像" width="130">
        <template scope="scope">
          <img :src="scope.row.adminAvatar" class="picture" />
        </template>
      </el-table-column>

    
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="priamry"
            @click="handleEdit(scope.row.adminId)"
            >编辑</el-button
          >
          <el-popconfirm
            title="这是一段内容确定删除吗？"
            @confirm="handleDelete(scope.row.adminId)"
          >
            <el-button size="mini" slot="reference" type="danger"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="query.pageIndex"
      :page-sizes="pageInfo.pageSizes"
      :page-size="query.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageInfo.total"
    >
    </el-pagination>

    <!--	添加-->
    <el-dialog title="添加管理员" :visible.sync="dialog.addshow" width="30%">
      <el-form ref="addForm" :model="addForm" label-width="80px" prop="did">
        <el-row>
          <el-col :span="24">
            <el-form-item label="电话" prop="adminTel">
              <el-input
                v-model="addForm.adminTel"
                placeholder="电话必填"
              ></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="adminPassword">
              <el-input
                v-model="addForm.adminPassword"
                placeholder="密码必填"
              ></el-input>
            </el-form-item>
            <el-form-item label="真实姓名" prop="adminNickname">
              <el-input v-model="addForm.adminNickname"></el-input>
            </el-form-item>

            <el-form-item label="头像路径" prop="adminAvatar" hidden>
              <el-input v-model="addForm.adminAvatar"></el-input>
            </el-form-item>

            <el-form-item label="部门" prop="deptId">
              <el-select
                v-model="addForm.deptId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in deptList"
                  :key="item.deptId"
                  :label="item.deptName"
                  :value="item.deptId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户头像">
              <el-upload
                ref="upload"
                :class="{ disUoloadSty: upload.uploadDisabled }"
                action="http://localhost:9000/admin/uploadoss"
                name="file"
                list-type="picture-card"
                :on-preview="handlePreview"
                :on-progress="onProgress"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                :before-upload="beforeUpload"
                :on-change="handleChange"
                :file-list="upload.fileList"
                accept=".jpeg,.jpg,.gif,.png"
                :limit="upload.limitCountImg"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <!--预览图片-->
              <el-dialog
                :modal-append-to-body="false"
                :visible.sync="upload.imgVisible"
                width="30%"
              >
                <img
                  width="100%"
                  :src="upload.dialogImageUrl"
                  alt="图片未找到"
                />
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.addshow = false">取 消</el-button>
        <el-button type="primary" @click="save()">确 定</el-button>
      </span>
    </el-dialog>

    <!--	修改-->
    <el-dialog
      title="编辑管理员信息"
      :visible.sync="dialog.updateshow"
      width="30%"
    >
      <el-form ref="updateForm" :model="updateForm" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="编号" prop="id" hidden>
              <el-input v-model="updateForm.adminTel" clearable></el-input>
            </el-form-item>

            <el-form-item label="电话" prop="adminTel">
              <el-input v-model="updateForm.adminTel"></el-input>
            </el-form-item>
    
            <el-form-item label="真实姓名" prop="adminNickname">
              <el-input v-model="updateForm.adminNickname"></el-input>
            </el-form-item>

            <el-form-item label="部门" prop="deptId">
              <el-select v-model="updateForm.deptId" style="width: 100%">
                <el-option
                  v-for="item in deptList"
                  :key="item.deptId"
                  :label="item.deptName"
                  :value="item.deptId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.updateshow = false">取 消</el-button>
        <el-button type="primary" @click="update()">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
export default {
  name: "Admin",
  data() {
    return {
      adminList: [],
      pageInfo: {
        pageSizes: [5, 10, 20, 50],
        total: "",
        pages: "",
      },
      //封装的请求参数
      query: {
        pageIndex: 1,
        pageSize: 5,
        adminNickname: "",
        adminStatus: "",
      },

      addForm: {},
      updateForm: {},
      deptList: {},
      dialog: {
        addshow: false,
        updateshow: false,
      },

      //-------上传文件相关数据------------------------------------------------------
      upload: {
        // 是否禁用上传，
        uploadDisabled: false,
        // 是否显示预览图片
        imgVisible: false,
        // 预览图片url
        dialogImageUrl: "",
        // 上传的文件列表（用于在上传组件中回显图片）, 例如: [{name: 'xxx.jpg', url: 'https://xxx.com/xxx.jpg'}]
        fileList: [],
        limitCountImg: 1, //上传图片的最大数量
      },
    };
  },
  methods: {
    //重置按钮
    reset() {
      (this.query.adminNickname = ""),
        (this.query.adminStatus = ""),
        this.loadAdmin();
    },

    //当每页显示条数改变时
    handleSizeChange(size) {
      this.query.pageSize = size;
      this.loadAdmin();
    },
    //当页数改变时
    handleCurrentChange(currentPage) {
      this.query.pageIndex = currentPage;
      this.loadAdmin();
    },
    loadAdmin() {
      this.$axios.post("admin/queryAllAdmin", this.query).then((res) => {
        this.adminList = res.data.data.list;
        this.pageInfo.pages = res.data.data.pages;
        this.pageInfo.total = res.data.data.total;
      });
    },
    loadDept() {
      this.$axios
        .get("admin/queryAllDept")
        .then((res) => {
          this.deptList = res.data.data;
        })
        .catch((error) => {
          this.$message.error("出错了，请稍后重试");
        });
    },
    save() {
      this.$axios
        .post("admin/regist", this.addForm)
        .then((res) => {
          if (res.data.code == 200) {
            this.$message.success("添加成功");
            this.dialog.addshow = false;
            this.loadAdmin();
          } else {
            this.$message.error(res.data.message);
          }
        })
        .catch((error) => {
          this.$message.error("出错了！请稍后重试");
        })
        .then(() => {
          //注意要指定prop="did"属性才能起作用
          this.$refs.addForm.resetFields();
        });
    },
    handleEdit(id) {
      this.$axios.get("admin/selAdminById/" + id).then((res) => {
        this.updateForm = res.data.data;
      });
      this.dialog.updateshow = true;
    },
    update() {
      this.$axios
        .put("admin/updateAdmin", this.updateForm)
        .then((res) => {
          if (res.data.code == 200) {
            this.$message.success("修改成功");
            this.dialog.updateshow = false;
            this.loadAdmin();
          } else {
            this.$message.error(res.data.message);
          }
        })
        .catch((error) => {
          this.$message.error("出错了！请稍后重试");
        })
        .then(() => {
          this.$refs.updateForm.resetFields();
        });
    },
    handleDelete(id) {
      this.$axios
        .delete("admin/delete/" + id)
        .then((res) => {
          if (res.data.code === 200) {
            this.$message.success("删除成功");
            this.loadAdmin();
          } else {
            this.$message.info("删除失败");
          }
        })
        .catch((error) => {
          this.$message.error("出错了！请稍后重试");
        });
    },

    //=======上传文件需要的方法===============================================================

    //文件上传成功的钩子函数
    handleSuccess(response, file, fileList) {
      this.$message.success("图片上传成功");

      if (response.code == 200) {
        this.upload.dialogImageUrl = response.message;
        this.addForm.adminAvatar = response.data; //将返回的文件储存路径赋值picture字段
      }
    },
    // 上传中
    onProgress(event, file, fileList) {
      this.upload.uploadDisabled = true;
    },
    //删除文件之前的钩子函数
    handleRemove(file, fileList) {
      this.$message.info("已删除原有图片");
      this.upload.uploadDisabled = fileList.length >= this.upload.limitCountImg;
    },
    //处理图片变化时
    handleChange(file, fileList) {
      this.upload.uploadDisabled = fileList.length >= this.upload.limitCountImg;
    },
    //点击列表中已上传的文件事的钩子函数
    handlePreview(file) {},
    //参数是上传的文件，若返回false，或返回Primary且被reject，则停止上传
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
  },
  mounted() {
    this.loadAdmin();
    this.loadDept();
  },
};
</script>

<style>
.uoloadSty .el-upload--picture-card {
  width: 110px;
  height: 110px;
  line-height: 110px;
}
.disUoloadSty .el-upload--picture-card {
  display: none; /* 上传按钮隐藏 */
}
.picture {
  width: 60px;
  height: 60px;
  border: 0px;
}
.disabled .el-upload--picture-card {
  display: none; /* 上传按钮隐藏 */
}
</style>